package com.zf.common.http.controller;

import com.zf.common.http.entity.FileFormEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * 代码调用多文件上传接口
 */
@Slf4j
@RestController
@RequestMapping("/test-file")
public class TestFileUploadController {

    /**
     * 上传表单，包含多个文件
     */
    @PostMapping(value = "/uploadMultiFile")
    public String upload(FileFormEntity formEntity) throws IOException {
        log.info("username: {}, age: {}", formEntity.getUsername(), formEntity.getAge());
        List<MultipartFile> attachFileList = formEntity.getAttachFileList();
        if (!CollectionUtils.isEmpty(attachFileList)) {
            for (MultipartFile file : attachFileList) {
                // 文件名
                String originalFilename = file.getOriginalFilename();
                log.info("originalFilename: {}", originalFilename);
                // 获取文件输入流
                InputStream inputStream = file.getInputStream();
                // 读取输入流内容
                byte[] fileBytes = FileCopyUtils.copyToByteArray(inputStream);
                if (fileBytes.length == 0) {
                    continue;
                }
                // 将读取的内容写入一个新的文件中
                Files.write(Paths.get("D:\\" + originalFilename), fileBytes);
            }
        }
        return "success";
    }

}
